<?php

namespace shopend\controllers;

use common\models\JurisdGroup;
use common\models\JurisdUser;
use common\models\Menu;
use common\models\Order;
use common\models\Shop;
use common\models\Complaint;
use Yii;
use common\service\ConstantService;
use common\service\GlobalUrlService;
use yii\base\Module;
use \yii\web\Response;
use yii\web\Controller;
use yii\web\Cookie;
use common\service\MenuService;

/**
 * 控制器基类.
 * Class BaseController
 * @package backend\controllers
 */
class BaseController extends Controller
{
    /**
     * 加密所用到的盐,请勿修改,上线时在改
     * @var string
     */
    protected  $salt = 'a321df354sa35d1f';

    /**
     * 所记录的cookie名,请修改成项目名.
     * @var string
     */
    protected  $auth_cookie = "group";

    protected $page_size = 2;

    protected $shop = null;

    protected $allow_actions = [
        'admin/login',
        'error/index',
        'shop/add-shop',
        'upload/get-token',
        'code/send-code',
        'shop/get-info',
        'shop/update-shop',
    ];

    public function __construct($id, Module $module, array $config = [])
    {
        parent::__construct($id, $module, $config);
        $view  = \Yii::$app->view;
        $view->params['id'] = $id;
        $this->layout  = "page";
        $this->getView()->title = '后台管理系统';
    }

    /**
     * 这里要初始化权限
     * @param \yii\base\Action $action
     * @return bool
     */
    public function beforeAction($action)
    {
        if(in_array($action->getUniqueId(),$this->allow_actions))
        {
            return true;
        }

        $is_login = $this->checkLoginStatus();

        if(!$is_login)
        {
            if($this->isAjax())
            {
                $this->renderJson(['url'=>GlobalUrlService::buildShopUrl('/admin/login')],'请重新登录',ConstantService::$response_fail);
            }
            $this->redirect(GlobalUrlService::buildShopUrl('/admin/login'));
            return false;
        }

        //这个地方写通知消息

        $this->getMessage($this->shop['id']);

        return true;
    }

    /**
     * 获取消息队列
     */
    private function getMessage($id)
    {
        //获取待审核的商家数量
        $dfh = Order::find()->where(['shop_id' => $id,'order_status'=>1,'pay_status'=>1])->count();
        $thz = Order::find()->where(['shop_id' => $id,'order_status'=>4,'pay_status'=>1])->count();
        $ts = Complaint::find()->where(['shop_id' => $id,'status'=>0])->count();
        $this->getView()->params['dfh'] = $dfh;
        $this->getView()->params['thz'] = $thz;
        $this->getView()->params['ts'] = $ts;
        $this->getView()->params['shop_count'] = $ts+$dfh+$thz;

    }


    private function checkLoginStatus()
    {
        $cookie = $this->getCookie($this->auth_cookie);

        if(!$cookie)
        {
            return false;
        }

        list($uid, $token) = explode('#',$cookie);

        if($uid && preg_match('/^\d+$/',$uid))
        {
            $shop_user = Shop::findOne(['id'=>$uid]);

            if($shop_user['status'] !=1){
                if($this->isAjax())
                {
                    $this->renderJson(['url'=>GlobalUrlService::buildShopUrl('/admin/login')],'商家状态异常请请联系管理员',ConstantService::$response_fail);
                }
                $this->redirect(GlobalUrlService::buildShopUrl('/admin/login'));
                return false;
            }

            if(!$shop_user)
            {
                $this->removeCookie($this->$shop_user);
                return false;
            }

            // 这里要查询一下用户信息.
            $access_token = $this->genToken($shop_user);
            // 这里代表登录成功.
            if($access_token == $token)
            {
                $this->shop = $shop_user;
                if(empty($shop_user['shop_logo'])){
                    $shop_user['shop_logo'] = '345734401912161877158695623.png';
                    $shop_user->save();

                }
                $this->getView()->params['current_user'] = $shop_user;
                return true;
            }
        }
        return false;
    }

    /**
     * 生成密钥.
     * @param $admin
     * @return string
     */
    protected function genToken(Shop $admin)
    {
        return md5(md5(implode('-',[
                $admin->primaryKey,
                $admin['user_account'],
                $admin['create_time'],
                $admin['password'],
            ])) . $this->salt);
    }
    /**
     * 返回pagejson
     * @param array $data
     * @param int $count
     * @param int $code
     * @throws \yii\base\ExitException
     * @return mixed
     */
    public function renderPageJson($data = [],$count = 0,$code = 0)
    {
        // 设置响应头信息.
        Yii::$app->response->format = Response::FORMAT_JSON;

        Yii::$app->response->data = [
            'data'  =>  $data,
            'count'   =>  $count,
            'code'  =>  $code
        ];

        return Yii::$app->end();
    }
    /**
     * 获取cookie值.
     * @param $cookie_name
     * @param string $default
     * @return mixed
     */
    private function getCookie($cookie_name,$default = '')
    {
        $cookies = Yii::$app->request->getCookies();
        return $cookies->getValue($cookie_name,$default);
    }

    /**
     * 删除Cookie
     * @param $cookie_name
     */
    protected function removeCookie($cookie_name)
    {
        $cookie_target = new Cookie([
            'name' => $cookie_name
        ]);
        $cookies = Yii::$app->response->cookies;
        $cookies->remove( $cookie_target );
    }

    /**
     * 添加cookie
     * @param string $cookie_name
     * @param string $value
     * @param int $expire
     */
    protected function addCookie($cookie_name,$value,$expire = 3600)
    {
        $cookies = Yii::$app->response->cookies;
        $cookies->add(new Cookie([
            'name' => $cookie_name,
            'value' => $value,
            'expire' => $expire? ( time() + $expire ):$expire,
            'path' => '/'
        ]));
    }

    /**
     * 判断是否为ajax请求.
     * @return bool|mixed
     */
    public function isAjax()
    {
        return Yii::$app->request->isAjax;
    }

    /**
     * 判断是否为post请求.
     * @return bool|mixed
     */
    public function isPost()
    {
        return Yii::$app->request->isPost;
    }

    /**
     * 判断是否为Get请求.
     * @return bool|mixed
     */
    public function isGet()
    {
        return Yii::$app->request->isGet;
    }

    /**
     * 获取queryString参数
     * @param string $key
     * @param string $default
     * @return array|string
     */
    public function get($key = '',$default = '')
    {
        $query = Yii::$app->request->getQueryParams();

        if(isset($query[$key]))
        {
            return $query[$key];
        }

        if(!$key)
        {
            return $query;
        }

        return $default;
    }

    /**
     * 获取post提交参数
     * @param string $key
     * @param string $default
     * @return array|string
     */
    public function post($key = '',$default = '')
    {
        $query = Yii::$app->request->getBodyParams();

        if(isset($query[$key]))
        {
            return $query[$key];
        }

        if(!$key)
        {
            return $query;
        }

        return $default;
    }

    /**
     * 渲染json请求.
     * @param array $data
     * @param string $msg
     * @param int $code
     */
    public function renderJson($data = [],$msg = '',$code = -1)
    {
        // 设置响应头信息.
        Yii::$app->response->format = Response::FORMAT_JSON;

        Yii::$app->response->data = [
            'data'  =>  $data,
            'msg'   =>  $msg,
            'code'  =>  $code,
            'req_id'=>  $this->geneReqId()
        ];

        return Yii::$app->end();
    }

    /**
     * 获取唯一值.
     * @return string
     */
    private function geneReqId()
    {
        return uniqid();
    }


}